package com.cloudfast.oauth.password;

import java.security.GeneralSecurityException;
import java.security.MessageDigest;
import java.security.SecureRandom;

import org.apache.commons.codec.DecoderException;
import org.apache.commons.codec.binary.Hex;
import org.apache.commons.lang3.Validate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

/**
 * @author liuyinwwei
 * @Description: 密码验证及对比登入密码
 * @date 2018年9月17日
 */
public class CloudPasswordEncoder extends BCryptPasswordEncoder {

    private static final String SHA1 = "SHA-1";
    private static SecureRandom random = new SecureRandom();

    /**
     * 密码对比
     *
     * @param rawPassword
     * @param encodedPassword
     * @return
     */
    @Override
    public boolean matches(CharSequence rawPassword, String encodedPassword) {
        byte[] salt = decodeHex(encodedPassword.substring(0, 16));
        byte[] hashPassword = sha1(rawPassword.toString().getBytes(), salt, 1024);
        return encodedPassword.equals(encodeHex(salt) + encodeHex(hashPassword));
    }

    /**
     * 密码加密
     *
     * @param rawPassword
     * @return
     */
    @Override
    public String encode(CharSequence rawPassword) {
        byte[] salt = generateSalt(8);
        byte[] hashPassword = sha1(rawPassword.toString().getBytes(), salt, 1024);
        return encodeHex(salt) + encodeHex(hashPassword);
    }

    /**
     * Hex编码.
     */
    private static String encodeHex(byte[] input) {
        return Hex.encodeHexString(input);
    }

    /**
     * Hex解码.
     */
    private static byte[] decodeHex(String input) {
        try {
            return Hex.decodeHex(input.toCharArray());
        } catch (DecoderException e) {
            throw new RuntimeException(e.getMessage());
        }
    }

    private static byte[] sha1(byte[] input, byte[] salt, int iterations) {
        return digest(input, SHA1, salt, iterations);
    }

    /**
     * 对字符串进行散列, 支持md5与sha1算法.
     */
    private static byte[] digest(byte[] input, String algorithm, byte[] salt, int iterations) {
        try {
            MessageDigest digest = MessageDigest.getInstance(algorithm);
            if (salt != null) {
                digest.update(salt);
            }
            byte[] result = digest.digest(input);

            for (int i = 1; i < iterations; i++) {
                digest.reset();
                result = digest.digest(result);
            }
            return result;
        } catch (GeneralSecurityException e) {
            return null;
        }

    }

    /**
     * 生成随机的Byte[]作为salt.
     *
     * @param numBytes byte数组的大小
     */
    private static byte[] generateSalt(int numBytes) {
        Validate.isTrue(numBytes > 0, "numBytes argument must be a positive integer (1 or larger)", numBytes);
        byte[] bytes = new byte[numBytes];
        random.nextBytes(bytes);
        return bytes;
    }
}
